var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var _Cart= require("../../modules/cart_module.js");
var Map = require("../../utils/map.js");
var app = getApp();

// 获取地图的返回信息
const chooseLocation = requirePlugin('chooseLocation');
// index.js
// const App = getApp();
Page({
  data: {
    navbg:'none',
    isBottom:false,
    current:1,
    bannerList: [],
    categoryList: [],
    couponList:{},
    goodList: [],
    userInfo:{},
    showModel:false,
    lastestCoupon:null,
    location: {
      latitude: 0,
      longitude: 0
    },
    mapName: "",
    allTarget: [],
    tagGoodsList: [],
    activityGoods: [],
    menuButton: {},
    numFlag:false,
    baokuaiList: [],
    hotList: [],
  },
  onPageScroll(e){
    if(e.scrollTop >= 170){
      this.setData({
        navbg:'#F96A42'
      })
    } else if(e.scrollTop < 170) {
      this.setData({
        navbg:'none'
      })
    }
  },
  onRefresh(){
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading();
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({
      title: '刷新中...',
    })
    this.onShow();
  },
  onPullDownRefresh: function () {
      //调用刷新时将执行的方法
    this.onRefresh();
  },
  onShow() {
    let userInfo = wx.getStorageSync('userInfo');
    let receiveNewCoupon = wx.getStorageSync('receiveNewCoupon')
    if(userInfo.receiveNewCoupon && !receiveNewCoupon){
      this.getLatestCoupon();
    }
    let token = wx.getStorageSync('token');
    // 页面显示
    if (userInfo && token) {
        app.globalData.userInfo = userInfo;
        app.globalData.token = token;
    }

    this.setData({
        userInfo: app.globalData.userInfo,
        current: 1,
        isBottom: false
    });
    this.getAllTarget();
    this.getBannerData();
    this.getIndexCategory();
    this.getGoodList();
    this.getGoodActivity();
    this.getCouponList();
    this.setData({
      navH: app.globalData.barHeight,
      menuButton: app.globalData.menuButton
    })
    // let location = wx.getStorageSync('location');

    // if(location){
    //   this.setData({
    //     location,
    //     mapName: location.name || ""
    //   })
    // }
    this.getAddressInfoList();
    if(app.globalData.cartNum > 0){
      wx.setTabBarBadge({
        index: 3,
        text: app.globalData.cartNum.toString()
      })
    }else{
      wx.removeTabBarBadge({index:3})
    }
    wx.hideLoading();
  },
  onLoad() {
    const location = wx.getStorageSync("location");
    // if(location){
    //   this.setData({
    //     location,
    //     mapName: location.name || ""
    //   })
    // }
    // this.getAllTarget();
  },
  /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function () {
    return {
        title: '108元福利放送中，仅限今天！', //转发页面的标题
        imageUrl: '/static/images/share.jpeg'

    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    chooseLocation.setLocation(null);
  },
  getLatestCoupon(){
    let _this = this;
    util.request(api.indexUrl.getLatestCoupon).then(res=>{
      this.setData({
        showModel:true,
        lastestCoupon:res.result
      })
    }).catch(err=>{
      console.log(err)
    }).finally(()=> wx.hideLoading());
  },
  // 轮播图
  getBannerData(){
    util.request(api.indexUrl.getBanner+"/1").then((res)=>{
      //console.log(res.result);
      if(res.result.length > 0){
        this.setData({
          bannerList:res.result
        })
      }
    }).finally(()=> wx.hideLoading());
  },
  closeModel() {

    wx.setStorageSync('receiveNewCoupon', true)
    this.setData({
      showModel:false
    })
  },
  getCouponList() {
    let _this = this;
    util.request(api.indexUrl.getCouponList).then(res=>{
      if(res.code==200){
        _this.setData({
          couponList:res.result
        })
      }

    }).finally(()=> wx.hideLoading());
  },
  // 首页分类
  getIndexCategory(){
    util.request(api.indexUrl.getIndexCategory).then((res)=>{
      //console.log(res.result);
      if(res.result.length > 0){
        this.setData({
          categoryList:res.result
        })
      }
    }).finally(()=> wx.hideLoading());
  },
  loadMore:function()
  {
     //页面触底执行分页逻辑
     this.findGoodsRequest();
  },
  onReachBottom: function () {
    if(this.data.isBottom){
      return
    }
    this.getGoodList();
  },
  // 商品列表
  getGoodList(){
    this.findGoodsRequest({
      isIndex: true
    }).then(res=>{
      if(res.result.length > 0){
        let data = [];
        if(this.data.current == 1){
          data = res.result;
        }else{
          data = this.data.goodList.concat(res.result);
        }
        this.setData({
          goodList:data,
          current:this.data.current+1
        })
      }else{
        this.setData({
          isBottom:true
        })
      }
    }).catch(err=>{
      console.log(err.message)
    }).finally(()=>{
      wx.hideLoading();
      wx.stopPullDownRefresh()
    })
  },
  // 活动商品列表
  getGoodActivity(){
    this.findGoodsRequest({
      isActivity: true
    }).then(res=>{
      if(res.result.length > 0){
        // if(res.result.length > 3){
        //   res.result.length = 3;
        // }
        this.setData({
          activityGoods: res.result
        })
      }
    }).catch(err=>{
      console.log(err.message)
    })
  },
  // 标签商品活动
  getGoodTagActivity(id){
    this.findGoodsRequest({
      commodityId: id
    }).then(res=>{

    }).catch(err=>{
      console.log(err.message)
    })
  },
  getGoodsByTag (data = {}) {
    wx.showLoading({
      title: "正在加载"
    })
    return new Promise((resolve, rejected)=>{
      util.request(api.indexUrl.FindCommodityByTarget, data, "GET").then((res)=>{
        //console.log("123", res.result);
        resolve(res);
        wx.hideLoading();
      }).catch(err=>{
        rejected(err);
        wx.hideLoading();
      }).finally(()=> wx.hideLoading());
    })
  },
  // 商品请求接口
  findGoodsRequest(data = {}){
    wx.showLoading({
      title: "正在加载"
    })
    let url = api.indexUrl.getGoodList;
    if(data.isIndex){
      url = api.indexUrl.getGoodList+'?current='+this.data.current+'&size='+10;
    }
    return new Promise((resolve, rejected)=>{
      util.request(url, data, "POST").then((res)=>{
        resolve(res);
        wx.hideLoading();
      }).catch(err=>{
        rejected(err);
        wx.hideLoading();
      }).finally(()=> wx.hideLoading());
    })
  },
  getAllTarget(){
    util.request(api.indexUrl.findAllTarget).then((res)=>{
      //console.log(res.result);
      if(res.result.length > 0){
        this.setData({
          allTarget:res.result
        })
        const tagGoodsList = []
        res.result.forEach(item=>{
          this.getGoodsByTag({
            id: item.id
          }).then(result=>{
            // if(result.result.length > 3){
            //   result.result.length = 3;
            // }
            tagGoodsList.push({
              type: "tag",
              id: item.id,
              name: item.name,
              goods: result.result
            })
            if(item.id == 1){
              this.setData({
                baokuaiList: result.result
              })
            }
            if(item.id == 3){
              this.setData({
                hotList: result.result
              })
            }
            this.setData({
              tagGoodsList,
            })
          }).finally(()=>{
            wx.hideLoading();
          })
        })
      }
    }).finally(()=> wx.hideLoading());
  },
  // 更新购物车
  async cartUpdate(e){
    console.log("enter cartUpdate e is",e)
    if(this.data.numFlag) return
    this.setData({
      numFlag:true,
    })
    //console.log(e);
    const data = e.detail;
    const type = e.type; //是增还是减
    let list = []
    if(data.type === "limit"){
      list = this.data.activityGoods;
    }else if(data.type === "baokuai" ){
      list = this.data.baokuaiList
    }else if(data.type === "hot"){
      list = this.data.hotList
    }else{
      list = this.data.goodList;
    }
    // 请求
    const res = await _Cart._cartUpdate({
      id: data.id,
      update: data.update,
      list,
      changeProperty: "hasNumber"
    }).catch(err=>{
      this.setData({
        numFlag:false,
      })
    });
    //console.log({res});
    // 本地更新购物车数量
    if(res){
      if(data.type === "limit"){
        const item_str = 'activityGoods[' + res.index + '].hasNumber'
        this.setData({
          [item_str]: res.num
        })
      }else if(data.type === "baokuai"){
        const item_str = 'baokuaiList[' + res.index + '].hasNumber'
        this.setData({
          [item_str]: res.num
        })
      }else if(data.type === "hot"){
        const item_str = 'hotList[' + res.index + '].hasNumber'
        this.setData({
          [item_str]: res.num
        })
      }else{
        const item_str = 'goodList[' + res.index + '].hasNumber'
        this.setData({
          [item_str]: res.num
        })
      }

    }
    this.setData({
      numFlag:false,
    })
  },
  // 地图事件
  toMap(){
    Map.getSetting(this.data.location);
  },
  //获取提货点
  getAddressInfoList:function() {
    let _this = this;
    wx.getLocation({
      type:'wgs84',
      success:function(res){

          util.request(api.findAddressInfoList+'?lat='+res.latitude+'&lon='+res.longitude).then(result=>{
              const chooseItem = result.result.find(item => item.isChoose) ;

              _this.setData({
                mapName: chooseItem.storeName || ""
              })
          }).catch(err=>{
              console.log(err)
          }).finally(()=> wx.hideLoading());

      },
      fail:function(err){
          console.log(err)
      }
    });

  },
})
